import { SelectionModel, SelectionType, TextModel } from "../models";
import BaseView from "./base_view";

export class SourceView extends BaseView{
  constructor (textModel: TextModel, selectionModel: SelectionModel, viewContainer: HTMLElement) {
    super(textModel, selectionModel, viewContainer);
    this.addEventListener();
  }

  addEventListener () : void{
    this._textModel.on('text_change', this.render.bind(this));
    this._selectionModel.on('selection_change', this.updateDomSelection.bind(this));
  }

  updateDomSelection () : void {
    // 如果当前编辑区没有元素，则无需设置选区
    if (!this._viewContainer.childNodes[0]) return;

    const domSelection: Selection | null = window.getSelection();
    if (domSelection) {
      const originSelection: SelectionType | null = this._selectionModel.getSelection();
      const anchor = originSelection?.anchor || 0;
      const focus = originSelection?.focus || 0;
      if (domSelection.anchorOffset === anchor && domSelection.focusOffset === focus) {
        return;
      }
      const range = document.createRange();
      range.setStart(this._viewContainer.childNodes[0], anchor);
      range.setEnd(this._viewContainer.childNodes[0], focus);
      domSelection.removeAllRanges();
      domSelection.addRange(range);
    }
  }

  render () {
    // 使用pre标签时，如果没有末尾补上一个换行符，光标的位置会不对
    this._viewContainer.innerHTML = this._textModel.getSpacers() + '\n';
    setTimeout(() => {
      this.updateDomSelection();
    }, 0);
  }
}

export default SourceView;